import java.util.PriorityQueue;

class MyTask implements Comparable<MyTask>{

    //Task类用于定义任务
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    //重写compareTo方法，放在优先级队列中的变量必须是可比较的
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
    public long getTime(){
        return this.time;
    }
    public Runnable getRunnable(){
        return this.runnable;
    }
}
public class MyTimer{
    PriorityQueue<MyTask> queue = new PriorityQueue<>();
    Object locker = new Object();
    //schedule中存在一个线程
    public void schedule(Runnable command, long after){
        synchronized (locker){
            MyTask myTask = new MyTask(command, after);
            queue.offer(myTask);
            locker.notify();
        }
    }
    //定义扫描线程
    Thread t = new Thread(()-> {
        while (true){
            synchronized (locker){
                while(queue.isEmpty()){
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                MyTask myTask = queue.peek();
                long currentTime = System.currentTimeMillis();
                if(currentTime >= myTask.getTime()){
                    queue.poll();
                    myTask.getRunnable().run();
                } else {
                    try {
                        //这里不可用sleep，防止又添加一新任务比当前任务更早时，无法唤醒线程
                        locker.wait(myTask.getTime() - currentTime);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                locker.notify();
            }
        }
    });

    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.t.start();
        myTimer.schedule(() -> System.out.println("500"), 500);
        myTimer.schedule(() -> System.out.println("1000"), 1000);
    }
}
